package com.xigege.netty.protocolDesignAndAnalysis.customProtocol.chatRoom.server;

import com.xigege.netty.protocolDesignAndAnalysis.customProtocol.chatRoom.server.handler.*;
import com.xigege.netty.protocolDesignAndAnalysis.customProtocol.protocol.MessageCodecSharable;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

import java.net.InetSocketAddress;

/**
 * 聊天室的案例，使用到自定义的协议（Message），消息解码编码器（MessageCodec）
 */
public class ChatServer {
    public static void main(String[] args) {
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup(2);
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC_SHARABLE = new MessageCodecSharable();
        LoginRequestMessageHandler LOGIN_HANDLER = new LoginRequestMessageHandler();
        ChatRequestMessageHandler CHAT_HANDLER = new ChatRequestMessageHandler();
        GroupCreateRequestMessageHandler GROUP_CREATE_HANDLER = new GroupCreateRequestMessageHandler();
        GroupJoinRequestMessageHandler GROUP_JOIN_HANDLER = new GroupJoinRequestMessageHandler();
        GroupMembersRequestMessageHandler GROUP_MEMBERS_HANDLER = new GroupMembersRequestMessageHandler();
        GroupQuitRequestMessageHandler GROUP_QUIT_HANDLER = new GroupQuitRequestMessageHandler();
        GroupChatRequestMessageHandler GROUP_CHAT_HANDLER = new GroupChatRequestMessageHandler();
        QuitHandler QUIT_HANDLER = new QuitHandler();
        try {
            ChannelFuture connectionFuture = new ServerBootstrap()
                    .group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            //加入netty提供的 IdleStateHandler 空状态的Handler
                            //（1）long readerIdleTime,表示server多长时间没有读取客服端发送的数据，就会发送一个心跳检测包，检测是否还是连接的状态
                            //（2）long writerIdleTime,表示server多长时间没有写数据给客服端，就会发送一个心跳检测包，检测是否还是连接的状态
                            //（3）long allIdleTime,表示多长时间既没有读也没有写，就会发送一个心跳检测包，检测是否还是连接的状态
                            // 5s内没有收到channel的数据，触发一个IdleState#READER_IDLE事件
                            ch.pipeline().addLast(new IdleStateHandler(5, 0, 0));
                            // ChannelDuplexHandler 可以同时作为入站和出站处理器
                            ch.pipeline().addLast(new ChannelDuplexHandler() {
                                // 用来触发特殊事件
                                @Override
                                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception{
                                    IdleStateEvent event = (IdleStateEvent) evt;
                                    // 触发了读空闲事件
                                    if (event.state() == IdleState.READER_IDLE) {
                                        System.out.println("已经 5s 没有读到数据了");
                                        // 5s没有读取到事件关闭通道
                                         ctx.channel().close();
                                    }
                                }
                            });
                            ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 12, 4, 0, 0));
                            ch.pipeline().addLast(LOGGING_HANDLER);
                            ch.pipeline().addLast(MESSAGE_CODEC_SHARABLE);
                            // 添加登录相关的handler
                            ch.pipeline().addLast(LOGIN_HANDLER);
                            // 添加聊天相关的handler
                            ch.pipeline().addLast(CHAT_HANDLER);
                            // 添加创建群组相关的handler
                            ch.pipeline().addLast(GROUP_CREATE_HANDLER);
                            // 添加加入群组相关的handler
                            ch.pipeline().addLast(GROUP_JOIN_HANDLER);
                            // 添加获取群组成员相关的handler
                            ch.pipeline().addLast(GROUP_MEMBERS_HANDLER);
                            // 添加退出群组相关的handler
                            ch.pipeline().addLast(GROUP_QUIT_HANDLER);
                            // 添加群聊相关的handler
                            ch.pipeline().addLast(GROUP_CHAT_HANDLER);
                            // 用户断开连接后的handler
                            ch.pipeline().addLast(QUIT_HANDLER);

                        }
                    }).bind(new InetSocketAddress(6666));
            Channel channel = connectionFuture.sync().channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
